package com.dily.study.demo.thread;

/**
 * Date: 2022-08-10 星期三
 * Time: 11:01
 * Author: Dily_Su
 * Remark:
 * 不安全的取钱(隐式锁)
 */
public class UnSafeBlank {

    public static void main(String[] args) {
        Account account = new Account(1000);
        Drawing you = new Drawing(account,50,"你");
        Drawing wo = new Drawing(account,100,"我");

        you.start();
        wo.start();
    }
}

class Account {
    int money;

    public Account(int money) {
        this.money = money;
    }
}

class Drawing extends Thread {
    Account account;
    String name;
    int drawingMoney;
    int nowMoney;

    public Drawing(Account account, int drawingMoney, String name) {
        this.account = account;
        this.drawingMoney = drawingMoney;
        this.name = name;
    }

    @Override
    public void run() {
       synchronized (account){
           if (account.money - drawingMoney < 0) {
               System.out.println(Thread.currentThread().getName() + "钱不够 取不了");
               return;
           }
           try {
               Thread.sleep(100);
           } catch (InterruptedException e) {
               e.printStackTrace();
           }

           account.money -= drawingMoney;
           nowMoney += drawingMoney;
           System.out.println("余额为" + account.money);
           System.out.println(this.name+"手里有" + nowMoney);
       }
    }
}